package cn.johnyu.controller;

import cn.johnyu.mapper.AccountMapper;
import cn.johnyu.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//Rest规范
//请求方法： GET :查询，POST: 添加，PUT: 更新，DELETE: 删除
// /[资源名]S: 表示对资源的请求
// /[资源名]S/[id]: 表示对某一资源的请求
//响应码： 2xx: 成功，3xx: 重定向，4xx : 资源不可用，5xx: 服务器内部错，1XX: 正在工作中
@RestController
//@CrossOrigin(allowedHeaders = "ACTION",origins = {"http://192.168.0.*:3000"})
@CrossOrigin
//tod:
public class AccountController {
    @Autowired
    private AccountMapper accountMapper;
    @GetMapping("/accounts")
    public List<Account> findAllAccounts(){
      return accountMapper.findAllAccounts();
    }

    @GetMapping("/info")
    public String info(){
        return "suc";
    }
    @GetMapping("/accounts/{id}")
    public ResponseEntity<Account> loadAccount(@PathVariable("id") int id){
        return ResponseEntity
                .status(200).body(accountMapper.loadAccountDetail(id));
//                .ok(accountMapper.loadAccount(id));
    }
//    @PutMapping("/accounts/{id}")
//
    @PostMapping("/accounts")
    public ResponseEntity<Account> addAccount(@RequestBody Account account){
        int rs = accountMapper.addAccount(account);
        if(rs>0) return ResponseEntity.ok(account);
        else return  ResponseEntity.status(460).body(null);
    }

//    @GetMapping("/accounts/{id}/orders/{oid}")
    @DeleteMapping("/accounts/{id}")
    public int deleteAccount(@PathVariable("id") int id){
        return accountMapper.deleteAccount(id);
    }

    @PutMapping("/accounts/{id}")
    public int udpateAccount(@PathVariable("id") int id,@RequestBody Account account){
        account.setId(id);
        int rs = accountMapper.updateAccount(account);
        return rs;
    }


}
